<template>
  <div ref="chartRef" :style="{ width: width, height: height }"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import 'echarts-gl'; // 导入 3D 支持

const props = defineProps({
  data: {
    type: Array,
    required: true,
    default: () => []
  },
  title: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  boxHeight: {
    type: Number,
    default: 0.1 // 默认立体高度
  }
});

const chartRef = ref(null);
let chartInstance = null;

// 初始化 ECharts 实例
onMounted(async () => {
  await nextTick(); // 确保 DOM 渲染完成
  chartInstance = echarts.init(chartRef.value);
  setOption();
});

// 设置 ECharts 配置
function setOption() {
  const option = {
    title: {
      text: props.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: props.data,
        // 3D 效果配置
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        },
        viewControl: {
          projection: 'orthographic', // 等距投影
          alpha: 70, // X 轴旋转角度
          beta: 15, // Y 轴旋转角度
          distance: 150 // 视角距离
        }
      }
    ],
    grid3D: {
      show: false,
      boxHeight: props.boxHeight, // 立体高度
      viewControl: {
        distance: 216,
        alpha: 24,
        beta: -45,
        autoRotate: false,
        zoomSensitivity: 0,
        rotateSensitivity: 0,
        panSensitivity: 0
      }
    }
  };
  chartInstance.setOption(option);
}

// 销毁 ECharts 实例
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>

<style scoped>
div {
  width: 100%;
  height: 100%;
}
</style>